<?php
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Request;

class Goods extends Adm
{
	use \app\admin\traits\Curd;
    public function index()
    {
    	return $this->fetch();
    }
    public function upload()
    {
    	$file = $this->request->file('file');
    	return $this->saveFile($file,'goods');
    }
    protected function filter_x($data){
        $fields = Db::query('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME =:table',['table'=>'goods']);
        $fields = array_column($fields,'COLUMN_NAME');

        foreach($data as $k=>$val){
            if(!in_array($k, $fields)){
                unset($data[$k]);
            }
        }
        return $data;
    }

    public function edit()
    {
        $id = Request::get('id','int');
        if($id){
            $data = ($this->_model)::find($id);
            if($data){
                $data['spec_names'] = json_encode($this->getGoodsAttr($id));
                $data['spec_values'] = json_encode($this->getGoodsSku($id));
            }
            $this->assign(get_defined_vars());
        }else{
            $this->status = 0;
        }

        return $this->fetch();
    }
    protected function getListByGid($table,$gid){
        return Db::table($table)->where(['goods_id'=>$gid])->select()->toArray();
    }
    protected function getGoodsAttr($gid){
        $spec_names = $this->getListByGid('goods_spec',$gid);
        $data = [];
        foreach ($spec_names as $k1 => $v1) {
            $name = $v1['name'];
            $data[$name] = [];
            $vals = Db::table('goods_spec_value')->where(['spec_id'=>$v1['id']])->select();
            foreach ($vals as $k2 => $v2) {
                $data[$name][] = $v2['name'];
            }
        }
        return $data;
    }
    protected function getGoodsSku($gid){
        $skus = Db::table('goods_sku')->where(['goods_id'=>$gid])->select()->toArray();
        $data = [];
        foreach ($skus as $k => $v) {
            $name = $v['group_str'];
            $data[$name] = [
                'id'=>$v['id'],
                'sku'=>$v['sku'],
                'num'=>$v['stock'],
                'price'=>$v['price'],
                'name'=>$v['group_str']
            ];
        }
        return $data;
    }

    public function create()
    {
        //属性遍历
        $spec_names = $this->data['spec_names'];
        //sku库存
        $sku_list = $this->data['spec_values'];

        Db::startTrans();
        $copy_spec_names = [];
        $xdata = $this->filter_x($this->data);
        try {
            
            $gid = Db::table('goods')->insertGetId($xdata);//商品插入
            if(!$gid){
                throw new \Exception("商品插入失败", 1);
            }
            echo 'goods';

            foreach ($spec_names as $specName => $specValues) {
                $id = Db::table('goods_spec')->insertGetId(['name'=>$specName,'goods_id'=>$gid]);
                if(!$id){
                    throw new \Exception("属性组：$specName创建失败", 1);
                }
                $copy_spec_names[$specName] = ['id'=>$id,'values'=>[]];
                foreach ($specValues as $k=>$specValue) {
                    $spec_val_id = Db::table('goods_spec_value')->insertGetId(['name'=>$specValue,'spec_id'=>$id]);
                    if(!$spec_val_id){
                        throw new \Exception("属性值：$specValue创建失败", 1);
                    }
                    $copy_spec_names[$specName]['values'][$specValue] = ['id'=>$spec_val_id];
                }
            }
            echo 'spec';
            
            foreach($sku_list as $sku_name=>$sku_info){
                $sku_str = $this->getSpecGroupStr($copy_spec_names,$sku_name);
                if($sku_str){
                    $sku['group_str'] = $sku_name;
                    $sku['sku_str'] = $sku_str;
                    $sku['stock'] = $sku_info['num'];
                    $sku['price'] = $sku_info['price'];
                    $sku_id = Db::table('goods_sku')->insertGetId($sku);
                    if(!$sku_id){
                        throw new \Exception("SKU：$sku_name插入失败", 1);
                    }
                }else{
                    //组合属性不存在的直接不存储
                }
            }
            echo 'sku';
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->code = 0;
            $this->msg = $e->getMessage();
            echo $this->msg;
        }
        return $this->fetch();
        /*
        $data = $this->_model::create($this->data);
        if(!$data->id){
            $this->code = 0;
            $this->msg = '创建失败!';
        }
        return $this->fetch();
        */
    }
    /**
     * [getSpecGroupStr 根据组合字符串 获取id组合信息]
     * @param  [type] $spec_names [description]
     * @param  [type] $group_str  [description]
     * @return [str]             [description]
     */
    protected function getSpecGroupStr($spec_names,$group_str)
    {
        $enable = true;
        $split_list = explode(',', $group_str);
        foreach ($split_list as $k => $item) {
            $split_arr = explode('|', $item);
            $name = $split_arr[0];
            $val = $split_arr[1];

            if( isset($spec_names[$name]) && isset($spec_names[$name]['values'][$val]) ){
                $split_list[$k] = $spec_names[$name]['id'].'|'.$spec_names[$name]['values'][$val]['id'];
            }else{
                $enable = false;
            }
        }
        if($enable){
            return implode(',' , $split_list);
        }
        return false;
    }
    public function test()
    {
        $c = $this->test2();
        var_dump($c);
        die;
    }
    public function test2()
    {
        return include '../app/admin/validate/test.php';
    }
}
